/* Copyright (C) 2008 Sahid Ferdjaoui <sahid@funraill.org>
 *
 *   This file is part of Postmemd.
 *
 * Postmemd is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


#ifndef PM_POOL_H
#define PM_POOL_H


#include "pm_poll.h"
#include "pm_head.h"
#include "pm_atom.h"

#include <ev.h>

/**
 * @file pm_slaves.h
 * @brief Postmem slaves
 */

typedef struct slave_hub {
	pid_t    pid;
	size_t   size;

	pfd_t     read;
	pfd_t     write;

	int       cmd;

	ev_io									event;
	struct ev_loop			*	loop;
} hub_t;


typedef struct slave {
	pid_t    pid;

	pfd_t    read;
	pfd_t    write;

	char   * rbuffer;              /** read buffer */
	int      rbuffer_bytes;        /** number of bytes readed */
	int      writed;

	struct json_object * json_obj;

	int cmd;
	char key[41];

	ev_io    event;
	struct ev_loop			*	loop;

	state_t state;

	struct slave * next;
	struct slave * prev;
} slave_t;


typedef struct pool_slaves {
	
	struct slave * first;
	struct slave * curr;
	struct slave * last;

	size_t size;
} pool_slaves_t;

void pm_slaves_init (pfd_t read_fd, pfd_t write_fd, struct ev_loop * loop);
void pm_slaves_process_loop (slave_t * slave);
void pm_slaves_read_fd (int fd, slave_t ** slave, char ** buffer, 
												int * buffer_bytes, state_t next);

int pm_slaves_parse_json (char * buffer, slave_t ** slave);

int pm_slave_del_atom (slave_t * slave, response_t * response);
int pm_slave_add_atom (slave_t * slave, response_t * response);
int pm_slave_get_atom (slave_t * slave, response_t * response);

/** pool slaves */
int pm_slaves_pool_init (pool_slaves_t ** pool);
int pm_slaves_pool_add (pool_slaves_t ** pool, pid_t pid, pfd_t in, pfd_t out, struct ev_loop * loop);
void pm_slaves_pool_view (pool_slaves_t * pool);
void pm_slaves_pool_change_curr (pool_slaves_t ** pool);
void pm_slaves_pool_select_curr (pid_t pid, pool_slaves_t ** pool);


#endif
